// 调整申请经费
<template>
  <layoutPage class="adj-application">
    <template #search>
      <vxe-form
        class-name="custom-form"
        :data="formSearch"
        title-align="right"
        align="left"
        title-width="120"
        @submit="handleSearch"
        @reset="handleReset"
      >
        <vxe-form-item
          title="审核状态："
          field="adjustStatus"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-select
              v-model="formSearch.adjustStatus"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in auditStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="课题类型："
          field="type"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-select v-model="formSearch.type" placeholder="请选择" clearable>
              <el-option
                v-for="item in _discStore.getDictType('topic_type')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="专业领域："
          field="subjectArea"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-tree-select
              v-model="formSearch.subjectArea"
              :data="_discStore.getDictType('professional_field')"
              :render-after-expand="false"
              placeholder="请选择"
              clearable
              filterable
            />
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="是否需要外协："
          field="externalCooperationRequired"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-select
              v-model="formSearch.externalCooperationRequired"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in _discStore.getDictType('yes_no')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="研究开始时间："
          field="researchStartDate"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-date-picker
              v-model="formSearch.researchStartDate"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="研究结束时间："
          field="researchEndDate"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-date-picker
              v-model="formSearch.researchEndDate"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="承担单位："
          field="leadingUnitId"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-tree-select
              v-model="formSearch.leadingUnitId"
              :data="deptInfoOptions"
              :render-after-expand="false"
              placeholder="请选择"
              filterable
              clearable
              check-strictly
              :props="{
                value: 'id',
                label: 'name',
                children: 'children',
              }"
            />
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="项目级别："
          field="projectLevel"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-select
              v-model="formSearch.projectLevel"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in _discStore.getDictType('project_level')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="项目类型："
          field="projectType"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-tree-select
              v-model="formSearch.projectType"
              :data="_discStore.getDictType('project_type')"
              :render-after-expand="false"
              placeholder="请选择"
              clearable
              filterable
            />
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="是否重点项目："
          field="keyProject"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-select
              v-model="formSearch.keyProject"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in _discStore.getDictType('yes_no')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="关键字："
          field="keyName"
          span="12"
          :item-render="{}"
        >
          <template #default>
            <div class="keyWord">
              <el-select
                v-model="formSearch.keyName"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in keyWordsOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-input
                v-model="formSearch.keyValue"
                placeholder="请输入"
                clearable
              />
            </div>
          </template>
        </vxe-form-item>
        <vxe-form-item span="24" align="right">
          <template #default>
            <el-button type="primary" native-type="submit">搜索</el-button>
            <el-button native-type="reset">重置</el-button>
          </template>
        </vxe-form-item>
      </vxe-form>
    </template>
    <template #default>
      <vxe-grid
        ref="xGrid"
        border
        stripe
        keep-source
        auto-resize
        sync-resize
        :loading="listLoading"
        :column-config="{ resizable: true }"
        :export-config="{}"
        :columns="tableColumn"
        align="left"
        show-overflow="tooltip"
        :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
      >
        <template #form>
          <div class="button-between">
            <el-button type="primary" @click="handleReport">
              经费调整申请上报
            </el-button>
            <el-button :loading="downLoading" plain @click="handleExport">
              导出搜索结果
            </el-button>
          </div>
          <div class="custom-divider"></div>
        </template>
        <template #options="{ row }">
          <el-button type="primary" link @click="handleDetails(row)">
            详情
          </el-button>
        </template>
        <template #bottom>
          <el-pagination
            background
            :current-page="formSearch.pageNo"
            layout="total, sizes, prev, pager, next, jumper"
            :page-size="formSearch.pageSize"
            :total="formSearch.total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </template>
      </vxe-grid>
    </template>
  </layoutPage>
</template>

<script lang="ts" setup>
  import layoutPage from '@/components/layoutPage.vue'
  import {
    formSearchProps,
    optionsProps,
    pagingProps,
    rowProps,
    resPageProps,
  } from './interface'
  import { getSimpleDeptList } from '@/api/system/dept'
  import {
    getFundingAdjustPage,
    getFundingAdjustExport,
  } from '@/api/project/researchFunds'
  import { useDictStore } from '@/store/modules/dict'
  import { useDepartmentTree, DepartmentNode } from '@/utils/useDepartmentTree'
  import { useDownload } from '@/utils/useDownload'

  const _discStore = useDictStore()

  // 审核状态 在这里去掉草稿 属性
  const auditStatus = computed(() => {
    const statusList = _discStore.getDictType('audit_status')
    return statusList.filter((item) => item.value !== '-1')
  })

  const tableColumn = [
    { title: '经费调整申请ID', field: 'adjustId', minWidth: 130 },
    { title: '追加金额(万元)', field: 'appendsAmount', minWidth: 180 },
    {
      title: '审核状态',
      field: 'adjustStatus',
      minWidth: 180,
      formatter: ({ cellValue }) => {
        return _discStore.getDictLabelForValue('audit_status', cellValue)
      },
    },
    {
      title: '课题类型',
      field: 'type',
      minWidth: 120,
      formatter: ({ cellValue }) => {
        return _discStore.getDictLabelForValue('topic_type', cellValue)
      },
    },
    { title: '专业领域', field: 'subjectAreaText', minWidth: 120 },
    {
      title: '研究开始时间',
      field: 'researchStartDate',
      minWidth: 160,
      formatter: ['formatDate', 'yyyy-MM-dd'],
    },
    {
      title: '研究结束时间',
      field: 'researchEndDate',
      minWidth: 160,
      formatter: ['formatDate', 'yyyy-MM-dd'],
    },
    { title: '预计投入经费(万元)', field: 'estimatedBudget', minWidth: 150 },
    {
      title: '是否需要外协',
      field: 'externalCooperationRequired',
      minWidth: 120,
      formatter: ({ cellValue }) => {
        return _discStore.getDictLabelForValue('yes_no', cellValue)
      },
    },
    { title: '承担单位', field: 'leadingUnitName', minWidth: 120 },
    { title: '协作单位', field: 'collaboratingUnitName', minWidth: 120 },
    { title: '项目编号', field: 'projectCode', minWidth: 120 },
    { title: '项目名称', field: 'projectName', minWidth: 120 },
    {
      title: '项目等级',
      field: 'projectLevel',
      minWidth: 120,
      formatter: ({ cellValue }) => {
        return _discStore.getDictLabelForValue('project_level', cellValue)
      },
    },
    { title: '项目类型', field: 'projectTypeName', minWidth: 120 },
    {
      title: '是否重点项目',
      field: 'keyProject',
      minWidth: 120,
      formatter: ({ cellValue }) => {
        return _discStore.getDictLabelForValue('yes_no', cellValue)
      },
    },
    { title: '项目负责人', field: 'headerName', minWidth: 120 },
    { title: '上报单位', field: 'reportingUnitName', minWidth: 120 },
    { title: '上报人', field: 'reporterName', minWidth: 120 },
    {
      title: '记录创建时间',
      field: 'createTime',
      minWidth: 160,
      formatter: ['formatDate', 'yyyy-MM-dd HH:mm:ss'],
    },
    {
      title: '操作',
      field: 'options',
      minWidth: 80,
      slots: { default: 'options' },
    },
  ]
  // 关键字变量
  const keyWordsOptions: optionsProps[] = [
    {
      label: '课题名称',
      value: 'topicName',
    },
    {
      label: '课题编号',
      value: 'topicCode',
    },
    {
      label: '课题负责人',
      value: 'topicLeader',
    },
    {
      label: '项目名称',
      value: 'projectName',
    },
    {
      label: '项目编号',
      value: 'projectCode',
    },
    {
      label: '项目负责人',
      value: 'headerName',
    },
    {
      label: '经费调整申请ID',
      value: 'adjustId',
    },
    {
      label: '上报人',
      value: 'adjustReport',
    },
  ]
  // 表格实例
  const xGrid = ref(null)
  // 加载状态
  const listLoading = ref<boolean>(false)
  // 查询表单
  const formSearch = reactive<formSearchProps & pagingProps>({
    pageNo: 1,
    pageSize: 10,
    total: 0,
  })

  // 搜索关键字处理
  const handleKeyWords = () => {
    const { keyName, keyValue, ...otherParams } = formSearch

    const searchParams = keyName
      ? { ...otherParams, [keyName]: keyValue }
      : { ...otherParams }

    return searchParams
  }
  // 搜索
  const handleSearch = async () => {
    const searchParams = handleKeyWords()
    try {
      listLoading.value = true
      const res: resPageProps = await getFundingAdjustPage(searchParams)
      if (res && res.code === 0 && res.data) {
        xGrid.value.reloadData(res.data?.list || [])
        formSearch.total = res.data?.total
      } else {
        xGrid.value.reloadData([])
      }
    } catch (e) {
      console.error('获取项目经费调整列表时出错:', e)
      xGrid.value.reloadData([])
    } finally {
      listLoading.value = false
    }
  }
  // 重置
  const handleReset = () => {
    formSearch.pageNo = 1
    formSearch.pageSize = 10
    formSearch.total = 0
    formSearch.keyValue = ''
    handleSearch()
  }

  // 分页大小变化
  const handleSizeChange = (val: number) => {
    formSearch.pageSize = val
    handleSearch()
  }

  // 当前页变化
  const handleCurrentChange = (val: number) => {
    formSearch.pageNo = val
    handleSearch()
  }
  // 获取上报单位
  const deptInfoOptions = ref<DepartmentNode[]>([])
  const handleDeptDetails = async () => {
    try {
      const res: any = await getSimpleDeptList()
      if (res && res.code === 0 && res.data) {
        deptInfoOptions.value = useDepartmentTree(res.data || [])
      }
    } catch (e) {
      console.error('获取上报单位出错:', e)
    }
  }
  // 组件挂载时执行
  onMounted(async () => {
    await Promise.all([handleSearch(), handleDeptDetails()])
  })

  // 导出搜索结果
  const { downLoading, downloadFile } = useDownload(
    getFundingAdjustExport,
    '项目经费调整列表.xls'
  )

  const handleExport = async () => {
    const searchParams = handleKeyWords()
    await downloadFile(searchParams)
  }

  // 路由实例
  const router = useRouter()

  // 难题上报
  const handleReport = () => {
    router.push({
      name: 'ResearchFunds_AdjApplication_Report',
    })
  }
  // 处理详情点击
  const handleDetails = (row: rowProps) => {
    router.push({
      name: 'ResearchFunds_AdjApplication_Details',
      query: { id: row.adjustId },
    })
  }
</script>

<style lang="scss" scoped>
  .adj-application {
    .keyWord {
      display: flex;
      align-items: center;
      width: 100%;
      .el-select {
        width: 30%;
      }
      .el-input {
        margin-left: 10px;
      }
    }
  }
</style>
